var util = require('../../utils/util.js');
var api = require('../../config/api.js');
const app = getApp()

class Message {
  userId = ''; //发送方
  parentId = ''; // 接收方
  pic = ''; // 为空时文本消息  有值时图片消息
  content = ''; // 内容
  createTime = util.formatTime(new Date())
  userOrderId = '' //订单Id
  constructor(userId, parentId, pic) {
    this.userId = userId;
    this.parentId = parentId;
    this.pic = pic;
  }
}
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    socketClient: null, //新聊天对象
    isIpx: true, //是否iphonex 
    msg: "", //输入的聊天内容 
    chatContentHeight: 0,
    msgList: [],
    userId: '', // 自己的id
    parentId: "", //聊天对象id
    openAvatarUrl: "", //自己的头像
    openId: "", //监听聊天当前用户的聊天信息
    userOrderId: "", //订单号
    avatarUrl: "" ,//自己方头像
    parent_avatarUrl:"", //对方头像
    scrollTop:0,
  },
  //事件处理函数
  bindMsgInput(e) {
    this.setData({
      msg: e.detail.value
    })
  },
  // 选择图片
  chooseImage() {
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var tempFilesSize = res.tempFiles[0].size;
        console.log(tempFilesSize)
        if (tempFilesSize >= 1024 *500){
          wx.showToast({
            title: '图片必须小于500KB',
            icon: 'none'
          });
          return
        }
        //启动上传等待中...  
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 10000
        })
        const tempFilePaths = res.tempFilePaths
        tempFilePaths.forEach((v, k) => {
          // 上传图片
          wx.uploadFile({
            url: api.UPLOAD_URL,
            filePath: v,
            name: 'image',
            header: {
              "Content-Type": "multipart/form-data" //记得设置
            },
            success(res) {
              if (res.statusCode == 200) {
                // let imageUrl = constants.API_BASE_URL + res.data
                wx.hideToast();
                let resJson = JSON.parse(res.data);
                let imageUrl = "https://knowif.oss-cn-beijing.aliyuncs.com/" + resJson.message
                console.log(imageUrl);
                that.sendImage(imageUrl)
              } else {
                wx.hideToast();
                wx.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false,
                  success: function(res) {}
                })
              }
            }
          })
        })
      }
    })
  },
  // 发送文本消息
  sendText() {
    let message = new Message(this.data.userId, this.data.parentId, null);
    message.content = this.data.msg;
    message.userOrderId = this.data.userOrderId
    this.sendSocketMessage(message);
    let msgList = this.data.msgList
    msgList.push(message)
    this.setData({
      msgList: msgList,
      msg: ''
    })
    this.scrollBottom();
  },
  // 发送图片消息
  sendImage(url) {
    let message = new Message(this.data.userId, this.data.parentId, "1");
    message.pic = url;
    message.userOrderId = this.data.userOrderId
    this.sendSocketMessage(message);
    let msgList = this.data.msgList
    msgList.push(message)
    this.setData({
      msgList: msgList,
      msg: ''
    })
    this.scrollBottom();
  },
  //统一发送消息
  sendSocketMessage: function(msg) {
    this.socketClient.send("/insertChat", {}, JSON.stringify(msg));
  },
  //接收消息
  socketReceiver: function(msg) {
    let msgList = this.data.msgList;
    msgList.push(msg.result);
    this.setData({
      msgList: msgList
    })
    this.scrollBottom();
  },
  //预览图片
  previewImage(e) {
    let imageMsgArr = this.data.msgList.filter(msg => {
      return msg.pic != null || msg.pic != '';
    })
    let imageArr = Array.from(imageMsgArr, img => img.pic)
    let target_Arr =[];
    for (let i of imageArr){
      if(i != null){
        target_Arr.push(i)
      }
    } 
    wx.previewImage({
      current: e.target.dataset.url, // 当前显示图片的http链接
      urls: target_Arr // 需要预览的图片http链接列表
    })
  },
  //滚动到底部
  scrollBottom:function(){
    //滚动到最底部
    let scrollTop = this.data.chatContentHeight * 100
    this.setData({
      scrollTop: scrollTop
    })
  },
  onLoad: function(option) {
    let that = this;
    //设置收发的id 用户头像
    let avatarUrl = wx.getStorageSync('userInfo').avatarUrl;

    let userId = option.user_id;
    let toUserId = option.to_user_id;
    if (userId == wx.getStorageSync('userInfo').id){
      this.setData({
        userId: option.user_id,
        parentId: option.to_user_id,
        userOrderId: option.orderId,
        avatarUrl: avatarUrl
      })
    }else{
      this.setData({
        userId: option.to_user_id,
        parentId: option.user_id,
        userOrderId: option.orderId,
        avatarUrl: avatarUrl
      })
    }

    //设置对方头像
    util.request(api.GetTUserImageById, {
      userId: that.data.parentId
    }, 'GET', false).then(function (res) {
      if (res.code == 200) {
        that.setData({
          parent_avatarUrl: res.message
        })
      } else {
        wx.showToast({
          title: '获取对方头像失败',
          icon: 'none'
        });
      }
    })
    
    //聊天ui
    let windowHeight = wx.getSystemInfoSync().windowHeight // 屏幕的高度
    let windowWidth = wx.getSystemInfoSync().windowWidth // 屏幕的宽度
    let ipxHeight = this.data.isIpx ? 64 : 30
    // 90顶部 接收方高度， 30底部paddingtop，  75 输入框高度
    this.setData({
      // openid: app.globalData.openid,
      // chatContentHeight: windowHeight * 750 / windowWidth - (90 + 30 + 75 + ipxHeight)
      chatContentHeight: windowHeight
    })

    //获取当前用户id
    this.userInfo = wx.getStorageSync('userInfo');
    if (this.userInfo == undefined || this.userInfo.id == undefined || this.userInfo.id == "" || this.userInfo.openid == "") {
      //没有用户信息跳转到登录界面
      wx.navigateTo({
        url: '/myPages/authorize/authorize'
      })
      return false;
    } else {
      this.setData({
        userId: this.userInfo.id,
        openAvatarUrl: this.userInfo.avatarUrl,
        openId: this.userInfo.openid
      })
    }

    //获取对方的用户id  历史记录
    util.request(api.GetUserChatList, {
      orderId: that.data.userOrderId
    }).then(function(res) {
      if (res.code === 200) {
        //有历史记录
        if (res.result.length > 0) {
          let tempArr = that.data.msgList.concat(res.result);
          that.setData({
            msgList: tempArr
          })
        }
      } else {
        wx.showToast({
          title: '获取对方信息失败',
          icon: ''
        });
      }
    });



    //初始化聊天 建立连接
    initWebsocket(that);


  },
  onShow: function () {
    //关闭分享
    wx.hideShareMenu()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.connectSocket({
      url: 'wss://www.zhishiya.online/webSocketServer'
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

})

function initWebsocket(that) {
  // socket是否连接
  var socketConnected = false;
  // 待发送的消息队列
  var messageQueue = [];
  // 是否断线重连
  var reconnect = true;


  // 发送消息
  function sendSocketMessage(msg) {
    // console.log(msg);
    // 如果socket已连接则发送消息
    if (socketConnected) {
      wx.sendSocketMessage({
        data: msg
      })
    } else {
      // socket没有连接将消息放入队列中
      messageQueue.push(msg);
    }
  }

  // 关闭连接
  function close() {
    if (socketConnected) {
      wx.closeSocket()
    }
  }

  // 符合WebSocket定义的对象
  var ws = {
    send: sendSocketMessage,
    close: close
  }

  // 创建一个 WebSocket 连接
  function connect() {
    wx.connectSocket({
      url: 'wss://www.zhishiya.online/webSocketServer'
    })
  }
  connect();

  // 监听 WebSocket 连接打开事件
  wx.onSocketOpen(function(res) {
    console.log("WebSocket 连接成功")
    socketConnected = true;
    ws.onopen();
    // 连接成功后，将队列中的消息发送出去
    let queueLength = messageQueue.length
    for (let i = 0; i < queueLength; i++) {
      const messageQueueElement = messageQueue.shift();
      wx.sendSocketMessage({
        data: messageQueueElement
      })
    }
  })

  // 监听 WebSocket 接受到服务器的消息事件
  wx.onSocketMessage(function(res) {
    ws.onmessage(res);
  })

  // 监听 WebSocket 错误事件
  wx.onSocketError(function(res) {
    console.log("WebSocket 错误事件")
  })

  // 监听 WebSocket 连接关闭事件
  wx.onSocketClose(function(res) {
    console.log("WebSocket 连接关闭")
    socketConnected = false;
    // 断线重连
    if (reconnect) {
      connect();
    }
  })

  var Stomp = require('../../utils/stomp.js').Stomp;

  /**
   * 定期发送心跳或检测服务器心跳
   *  The heart-beating is using window.setInterval() to regularly send heart-beats and/or check server heart-beats.
   *  可看stomp.js的源码（195,207，489行），由于小程序没有window对象，所以我们要调用小程序的定时器api实现
   */
  Stomp.setInterval = function(interval, f) {
    return setInterval(f, interval);
  };
  // 结束定时器的循环调用
  Stomp.clearInterval = function(id) {
    return clearInterval(id);
  };

  var stompClient = Stomp.over(ws);
  //定义给小程序对象
  that.socketClient = stompClient

  stompClient.connect({}, function(callback) {

    // 主题订阅
    // stompClient.subscribe('/user/test/oop', function (body, headers) {
    //   console.log('收到群发消息', body);
    // });

    // 订阅自己的id 接收后台接收过来的消息
    stompClient.subscribe('/user/' + that.data.openId+'/oop', function(message, headers) {
      wx.vibrateLong()
      console.log('收到只发送给我的消息:', message);
      // 通知服务端收到消息
      that.socketReceiver(JSON.parse(message.body));
      message.ack();
    });

    // 向服务端发送消息
    stompClient.send("/wechat/add", {}, JSON.stringify({
      'msg': '我是客户端'
    }));
  })

}